package com.news.controller;


import com.news.model.Admin;
import com.news.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RequestMapping("/admin")
@Controller
public class AdminController {
    @Autowired
    private AdminService adminService;

    //登录
    @RequestMapping("/login")
    public String login(Admin admin, HttpSession session){
        List<Admin> admin1 = adminService.selectAdmin(admin.getName());
        for(Admin admin2 :admin1){
            if(admin2.getPassword().equals(admin.getPassword()) && admin2.getStatus() !="1"){
                session.setAttribute("admin",admin2);
                return "redirect:/index.jsp";
            }
            else{
                return "redirect:/login.jsp";
            }
        }
        return "404";
    }
    //添加
    @RequestMapping("/insert")
    public void insert(Admin admin, HttpServletResponse response) throws IOException {
        System.out.println("测试");
        admin.setId(UUID.randomUUID().toString().replace("-",""));
        admin.setStatus("0");
        admin.setTime(new Date());
        adminService.insert(admin);
        PrintWriter out = response.getWriter();
        out.print("valid");
        out.flush();
        out.close();
       // return "redirect:/admin/query/1/10";
    }
    //查询一个
    @RequestMapping("/queryOne")
    public String queryOne(Admin admin, Model model){
        Admin admin1 = adminService.queryOne(admin.getId());
        model.addAttribute("admin",admin1);
        return "admin-update";
    }
    // 修改
    @RequestMapping("/update")
    public void update(Admin admin){
        System.out.println(admin);
        adminService.update(admin);
       // return "redirect:/admin/query/1/10";
    }
    // 启用停用
    @RequestMapping("/updateStatus")
    public void updateStatus(String id){
        System.out.println(id);
        Admin admin1 = adminService.queryOne(id);
        if("1".equals(admin1.getStatus())){
            admin1.setStatus("0");
        }else{
            admin1.setStatus("1");
        }
        adminService.updateStatus(admin1);
    }
    @RequestMapping("/query/{pageNum}/{pageSize}")
    public String query(Model model, @PathVariable("pageNum")int pageNum, @PathVariable("pageSize") int pageSize){
        List<Admin> admins = adminService.queryAll(pageNum,pageSize);
        model.addAttribute("admins",admins);
        return "admin-list";
    }
}
